package one.jieyun.ajzw;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import one.jieyun.ajzw.adapter.HomeAdapter;
import one.jieyun.ajzw.module.ListViewItem;
import one.jieyun.ajzw.module.ListViewSubItem;
import one.jieyun.ajzw.module.NetUtils;

/**
 * Created by Administrator on 2016/9/8.
 */
public class Fragment_Home extends Fragment {
    private ListView lvData;
    private SwipeRefreshLayout mSwipeLayout;
    private HomeAdapter homeAdapter;
    private String TAG = "FragmentHome->";
    private Context context;
    private View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.fragment_home, null);
            lvData = (ListView)rootView.findViewById(R.id.listview);
        }
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (null != homeAdapter) {
            return;
        }

        Log.i(TAG,"onActivityCreated");
        context = getContext();
        Activity myActivity = this.getActivity();
        mSwipeLayout = (SwipeRefreshLayout) myActivity.findViewById(R.id.swipeRefresh);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData();
            }
        });
        loadData();
    }

    private void loadData(){
        //开始请求数据
        mSwipeLayout.setRefreshing(true);
        RemoteDataSource rs = new RemoteDataSource();
        Random random=new Random();
        rs.execute("http://m.scykw.cn/api/ajzw/home.json?q="+random.nextInt());
    }

    private void FillListView(List<ListViewItem> list){
        lvData.setAdapter(null);
        homeAdapter = new HomeAdapter(context, list);
        lvData.setAdapter(homeAdapter);
        mSwipeLayout.setRefreshing(false);
    }

    private class RemoteDataSource extends AsyncTask<String, Integer, List<ListViewItem>> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected List<ListViewItem> doInBackground(String... params) {
            Log.i(TAG, "开始请求数据...:" );
            String context = NetUtils.get(params[0]);

            if(context == null){
                Log.i(TAG, "无结果...:" );
                return null;
            }

            Log.i(TAG, "请求结果...:"+context );

            try {
                JSONObject jsonObject = new JSONObject(context);
                List<ListViewItem> msgList = new ArrayList<ListViewItem>();

                //顶端Slider
                List<ListViewSubItem> sliders = new ArrayList<ListViewSubItem>();
                JSONArray strArr = jsonObject.getJSONArray("sliders");
                for(int i=0;i<strArr.length();i++){
                    JSONObject obj = strArr.getJSONObject(i);
                    int id= obj.getInt("id");
                    String title = obj.getString("title");
                    String image = obj.getString("image");
                    String url = obj.getString("url");

                    sliders.add(new ListViewSubItem(id,title,image,url));
                }
                msgList.add(new ListViewItem(ListViewItem.ItemType_Slider,sliders));

                //第二栏
                JSONArray optsArr = jsonObject.getJSONArray("opts");
                List<ListViewSubItem> opts_items = new ArrayList<ListViewSubItem>();
                for(int i=0;i<optsArr.length();i++){
                    JSONObject obj = optsArr.getJSONObject(i);
                    int id= obj.getInt("id");
                    String title = obj.getString("title");
                    String image = obj.getString("image");
                    String url = obj.getString("url");

                    opts_items.add(new ListViewSubItem(id,title,image,url));
                }
                msgList.add(new ListViewItem(ListViewItem.ItemType_Opts,opts_items));

                //第三栏新闻
                JSONArray newsArr = jsonObject.getJSONArray("news");
                List<ListViewSubItem> news_items = new ArrayList<ListViewSubItem>();
                for(int i=0;i<newsArr.length();i++){
                    JSONObject obj = newsArr.getJSONObject(i);
                    int id= obj.getInt("id");
                    String title = obj.getString("title");
                    String image = obj.getString("image");
                    String url = obj.getString("url");

                    news_items.add(new ListViewSubItem(id,title,image,url));
                }
                msgList.add(new ListViewItem(ListViewItem.ItemType_News,news_items));

                //第四栏
                JSONArray hotArr = jsonObject.getJSONArray("hotProject");
                List<ListViewSubItem> hot_items = new ArrayList<ListViewSubItem>();
                for(int i=0;i<hotArr.length();i++){
                    JSONObject obj = hotArr.getJSONObject(i);
                    int id= obj.getInt("id");
                    String title = obj.getString("title");
                    String image = obj.getString("image");
                    String url = obj.getString("url");

                    hot_items.add(new ListViewSubItem(id,title,image,url));
                }
                msgList.add(new ListViewItem(ListViewItem.ItemType_HotProject,hot_items));

                Log.i(TAG, "Result:" + msgList);


                return msgList;
            } catch (JSONException e) {
                Log.i(TAG, "Error:" + e);
                return null;
            }
        }

        /**
         * 这里的String参数对应AsyncTask中的第三个参数（也就是接收doInBackground的返回值）
         * 在doInBackground方法执行结束之后在运行，并且运行在UI线程当中 可以对UI空间进行设置
         */
        @Override
        protected void onPostExecute( List<ListViewItem> result) {
            Log.i(TAG, "异步操作执行结束:");
            if(result != null){
                Log.i(TAG, "result->"+result);
                FillListView(result);
            }
        }

        //该方法运行在UI线程当中,并且运行在UI线程当中 可以对UI空间进行设置
        @Override
        protected void onPreExecute() {
            Log.i(TAG,"开始执行异步线程");
        }

        /**
         * 这里的Intege参数对应AsyncTask中的第二个参数
         * 在doInBackground方法当中，，每次调用publishProgress方法都会触发onProgressUpdate执行
         * onProgressUpdate是在UI线程中执行，所有可以对UI空间进行操作
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.i(TAG,"完成:" + values);
        }
    }
}
